<template>
  <view class="map-page">
    <van-nav-bar :title="scrolling? navBarTitle : '选择位置' " left-arrow @click-left="onClickLeft"> </van-nav-bar>
    <view class="header">
      <!-- <text @click="cancel">取消</text> -->
      <map id="map" style="width: 100%; min-height:50vh;"  :latitude="latitude" :longitude="longitude" :scale="16" @markertap="markerTap" @callouttap="calloutTap"></map>
      <!-- <text @click="confirm" class="complete-btn">完成</text> -->
    </view>
    <view class="search-bar">
      <input type="text" placeholder="搜索地点" v-model="searchValue" />
    </view>
    <view class="location-list">
      <view v-for="(location, index) in locationList" :key="index" @click="selectLocation(location)">
        <text>{{location.name}}</text>
        <text>{{location.distance}} | {{location.address}}</text>
      </view>
      <view class="confirm-btn" @click="confirm">确认选择</view>
    </view>
  </view>
</template>
<script>

import Dialog from '@/wxcomponents/vant/dialog/dialog'
import isShouhuoPopup from '@/mycomponents/shangcheng/isShouhuoPopup.vue'
import {getMyServiceApi} from '@/api/mine'
const chooseLocation = requirePlugin('chooseLocation');

export default {

  props: {

  },
  components: {
      isShouhuoPopup
  },
  data () {
      return {
        navBarTitle: '导航',
        scrolling: false,
        latitude: 35.0441, // 示例纬度，可根据实际需求调整
        longitude: 110.9738, // 示例经度，可根据实际需求调整
        searchValue: '',
        locationList: [
          {
            name: '盐湖区运城经开政务中心西南50米(涑水东街北)',
            distance: '100m内',
            address: '盐湖区'
          },
          {
            name: '天地装饰体验中心',
            distance: '100m内',
            address: '盐湖区涑水街运城经开政务中心旁'
          },
          // 可根据实际情况添加更多地点数据
        ],
        selectedLocation: null,

      }
  },

  computed: {},
  watch: {},
  onLoad(data) {
  
    // 直接打开地图选点界面
    debugger
    this.openMapPicker();
  },
  onReady () { },
  onShow() {
    const selectedLocation = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
		console.log('选择的位置：', selectedLocation);
  },
  methods: {
    // 滑动
    scrollPage(e) {
      console.log(e.detail.scrollTop, this.scrolling)
      if (e.detail.scrollTop > 25 && !this.scrolling) {
        this.scrolling = true
      } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
        this.scrolling = false
      }
    },
    // 返回键
    onClickLeft() {
      uni.navigateBack()
    },
    cancel() {
      uni.navigateBack();
    },
    async openMapPicker() {
      // 检查是否支持地图选点插件
      if (!chooseLocation) {
        uni.showToast({ title: '当前微信版本不支持地图选点功能', icon: 'none' });
        return;
      }
      const key = '3LMBZ-65DKB-MCBUG-NVM5T-4PSX5-PWBGL'; //使用在腾讯位置服务申请的key
      const referer = '17乐生活'; //调用插件的app的名称
      const location = JSON.stringify({
        latitude: 39.89631551,
        longitude: 116.323459711,
      });
      // const category = '生活服务,娱乐休闲';

      // 创建页面跳转事件通道
      const eventChannel = this.getOpenerEventChannel();
      console.log('location', 'zooooo')
      wx.navigateTo({
        url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}`,
        events: {
          // 监听地图选点完成事件
          chooseLocation: (res) => {
            console.log('选择的位置信息:', res);
            // 将选择的位置信息更新到表单
            if (res) {
              this.userInfo.address = `${res.province || ''} ${res.city || ''} ${res.district || ''}`.trim();
              this.userInfo.detailAddress = res.address || res.name || '';
            }
          }
        },
        success: (res) => {
          console.log('地图插件打开成功');
          // 设置30秒超时检测
          setTimeout(() => {
            if (!this.positionSelected) {
              console.log('用户取消了位置选择');
            }
          }, 30000);
        },
        fail: (err) => {
          console.error('打开地图失败:', err);
          Toast.fail('无法打开地图');
        }
      });
      console.log('location', 'zoooowwwo')
    },

    calcDistance(lat, lng) {
      // 简单计算距离（示例用，实际应使用地图API）
      const R = 6371; // 地球半径
      const dLat = (lat - this.latitude) * Math.PI / 180;
      const dLon = (lng - this.longitude) * Math.PI / 180;
      const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(this.latitude * Math.PI / 180) * Math.cos(lat * Math.PI / 180) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return (R * c * 1000).toFixed(0) + '米';
    },

    // confirm() {
    //   console.log('确认选择',this.locationList)
    //   if (this.locationList.length > 0) {
    //     const selected = this.locationList[0];
    //     console.log(selected, 'selected选择的地点')
    //     uni.navigateBack({
    //       success: () => {
    //         const eventChannel = this.getOpenerEventChannel();
    //         eventChannel.emit('selectedLocation', {
    //           // name: selected.name,
    //           // address: selected.address,
    //           // latitude: selected.latitude,
    //           // longitude: selected.longitude
    //           fullAddress: `${selected.name} ${selected.address}`, // 组合完整地址
    //           detail: {
    //             province: selected.province || '山西省', // 根据实际数据结构调整
    //             city: selected.city || '运城市',
    //             district: selected.district || '盐湖区',
    //             address: selected.address,
    //             latitude: selected.latitude,
    //             longitude: selected.longitude
    //           }
    //         });
    //       }
    //     });
    //   }
    // },
    selectLocation(location) {
      // 处理点击地点列表项的逻辑，例如更新地图中心位置等
    },
    markerTap(e) {
      // 处理点击地图标记的逻辑
    },
    calloutTap(e) {
      // 处理点击地图标注气泡的逻辑
    }

  }

}
</script>
<style lang="scss" scoped>
.map-page {
  height: 100vh;
}
.header {
  position: relative;
  height:40vh;
  width: 100%;
}
.complete-btn {
  position: absolute;
  top: 0;
  right: 0;
  padding: 0 20rpx;
  line-height: 80rpx;
  color: green;
}
.search-bar {
  margin-top: 50px;
  padding: 10rpx;
  background-color: #f5f5f5;
}
.location-list view {
  padding: 10rpx;
  border-bottom: 1rpx solid #ccc;
}
</style>
